//
//  TuiTeAppDelegate.m
//  TuiTe
//
//  Created by 张 霄鹤 on 10-3-3.
//  Copyright xhzhang 2010. All rights reserved.
//

#import "TuiTeAppDelegate.h"
#import "DataManager.h"
#import "ProfileImageProcesser.h"

#define SETTING_INDEX 3

@implementation TuiTeAppDelegate

@synthesize window;
@synthesize tabBarController;
@synthesize navigationController;


#pragma mark -
#pragma mark Application lifecycle

// - (void)applicationDidFinishLaunching:(UIApplication *)application
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
	
	// [FlurryAPI startSession:@"38PTKX3RQI2NM6GJRBK7"];
#ifdef DEBUG
	NSLog(@"finish launching");
#endif
	DataManager *dm = [DataManager sharedManager];
	dataManager = dm;
	dm.managedObjectContext = [self managedObjectContext];
    
    // Override point for customization after app launch  
	
	// TODO 检查用户信息，如果有则进入程序，无则显示其它的界面
	BOOL bok = [dm loadAccounts];
	NSUserDefaults *usr = [NSUserDefaults standardUserDefaults];
	if(!bok){
		[tabBarController setSelectedIndex:SETTING_INDEX];
	}else{
		
		NSInteger ti = [usr integerForKey:@"ti"];
		[tabBarController setSelectedIndex:ti];
		ProfileImageProcesser *pp = [ProfileImageProcesser getInstance];
		[pp loadImagesFromData];
	}
	NSString *cf = [usr stringForKey:@"cf"];
	if(cf){
		dm.proxyAddress = cf;
	}
	// [window addSubview:[tabBarController view]];
	UINavigationController *nc = [[UINavigationController alloc] init];
	nc.navigationBar.barStyle = UIBarStyleBlack;
	NSArray *vcs = [[NSArray alloc] initWithObjects:tabBarController,nil];
	self.navigationController = nc;
	[self.navigationController setViewControllers:vcs];
	[vcs release];
	[nc release];
	[window addSubview:self.navigationController.view];
	[window makeKeyAndVisible];
	
	NSData *dt = [DataManager loadBinaryFromFile:@"devtoken.dat"];
	if(dt == nil){
		[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
	}
	
	return YES;
}

#pragma mark -
#pragma mark iOS4_Delegate_Add
/*
 
 iOS4 MultiTask,
 
 Application Startup and end steps:
 
 -----------1-------------
 2010-07-29 00:54:31.512 TuiTe[892:307] finish launching
 2010-07-29 00:54:37.112 TuiTe[892:307] applicationDidBecomeActive
 
 -----------2-------------
 2010-07-29 00:55:36.515 TuiTe[892:307] applicationWillResignActive
 2010-07-29 00:55:36.522 TuiTe[892:307] applicationDidEnterBackground
 
 -----------3-------------
 2010-07-29 00:58:23.318 TuiTe[892:307] applicationWillEnterForeground
 2010-07-29 00:58:23.332 TuiTe[892:307] applicationDidBecomeActive
 
 -----------4-------------
 2010-07-29 01:00:02.356 TuiTe[892:307] applicationWillResignActive
 2010-07-29 01:00:05.536 TuiTe[892:307] applicationDidEnterBackground
 
 
 1 is click the app icon and app launch and run
 2 is click home button, the app switch background but not exit
 3 is double-click home button, list the background apps, and select this app, then reload app.
 4 is double-click home button, list the background apps, and long-click this app, and delete this app from background, and receive
 
 */



- (void)applicationDidBecomeActive:(UIApplication *)application{
	NSLog(@"applicationDidBecomeActive");
}

- (void)applicationWillResignActive:(UIApplication *)application{
	NSLog(@"applicationWillResignActive");
}

- (void)applicationDidEnterBackground:(UIApplication *)application{
	NSLog(@"applicationDidEnterBackground");
}

- (void)applicationWillEnterForeground:(UIApplication *)application{
	NSLog(@"applicationWillEnterForeground");
}

#pragma mark -

/**
 applicationWillTerminate: saves changes in the application's managed object context before the application terminates.
 */
- (void)applicationWillTerminate:(UIApplication *)application {
	
    NSError *error = nil;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
			/*
			 Replace this implementation with code to handle the error appropriately.
			 
			 abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
			 */
			NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
			abort();
        } 
    }
	// DataManager *dm = [DataManager sharedManager];
	ProfileImageProcesser *pp = [ProfileImageProcesser getInstance];
	[pp saveImagesToData];
	// [pp release];
	// [dm release];
	NSInteger ti = tabBarController.selectedIndex;
	NSUserDefaults *usr = [NSUserDefaults standardUserDefaults];
	[usr setInteger:ti forKey:@"ti"];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
	NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
	[center postNotificationName:@"RECV_TUITE" object:url];
	return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
#ifdef DEBUG
	NSLog(@"Recive Device Token");
#endif
    [DataManager saveBinaryToFile:deviceToken withName:@"devtoken.dat"];
	// DataManager *dm = [DataManager sharedManager];
	// dm.token = deviceToken;
	[NSThread detachNewThreadSelector:@selector(updateDeviceToken:) toTarget:self withObject:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
	id obj = [userInfo objectForKey:@"cf"];
	if(obj){
		NSString *cfgURL = (NSString *)obj;
		NSUserDefaults *usr = [NSUserDefaults standardUserDefaults];
		[usr setObject:cfgURL forKey:@"cf"];
		DataManager *dm = [DataManager sharedManager];
		dm.proxyAddress = cfgURL;
	}
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
	NSLog(@"%@",error);
}

#pragma mark -

- (void)updateDeviceToken:(NSData *)token{
	//DataManager *dm = [DataManager sharedManager];
	//NSInteger num = [dm numberOfAccounts];
	NSURL *url = [[NSURL alloc] initWithString:@"http://vhlyserver.appspot.com/aps"];
	NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
	[url release];
	[req setHTTPMethod:@"POST"];
	NSMutableData *md = [[NSMutableData alloc] init];
	UIDevice *device = [UIDevice currentDevice];
	char bs[4];
	bs[0] = 0;
	bs[1] = 0;
	[md appendBytes:bs length:2];
	[md appendData:token];
	NSMutableString *sb = [[NSMutableString alloc] init];
	[sb appendFormat:@"DEV:%@|%@ - %@|%@|%@",device.model,device.systemName,device.systemVersion,device.name,@"TuiTe"];
	NSData *d1 = [sb dataUsingEncoding:NSUTF8StringEncoding];
	NSInteger ll = [d1 length];
	bs[0] = (ll & 0x0ff00)>>8;
	bs[1] = ll & 0x0ff;
	[md appendBytes:bs length:2];
	[md appendData:d1];
	
	NSInteger pt = PRODUCT_TYPE;
	bs[0] = (pt & 0x0ff000000)>>24;
	bs[1] = (pt & 0x0ff0000)>>16;
	bs[2] = (pt & 0x0ff00)>>8;
	bs[3] = (pt & 0x0ff);
	[md appendBytes:bs length:4];
	
	[req setHTTPBody:md];
	NSString *slen = [[NSString alloc] initWithFormat:@"%d",[md length]];
	[req addValue:slen forHTTPHeaderField:@"Content-Length"];	
	[req setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
	[req addValue:@"TuiTe/1.0 (gzip)" forHTTPHeaderField:@"User-Agent"];

	NSHTTPURLResponse *resp;
	NSError *err;
	NSData *dt = [NSURLConnection sendSynchronousRequest:req returningResponse:&resp error:&err];
	
	[sb release];
	if(dt == nil && err != nil){
		[err release];
	}else{
		[resp release];
	}
	[slen release];
	[md release];
	[req release];
}



#pragma mark -
#pragma mark Core Data stack

/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext *) managedObjectContext {
	
    if (managedObjectContext != nil) {
        return managedObjectContext;
    }
	
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator: coordinator];
    }
    return managedObjectContext;
}


/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created by merging all of the models found in the application bundle.
 */
- (NSManagedObjectModel *)managedObjectModel {
	
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];    
    return managedObjectModel;
}


/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
	
    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }
	
    NSURL *storeUrl = [[NSURL alloc] initFileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"TuiTe.sqlite"]]; 
	// [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"TuiTe.sqlite"]];
	
	NSError *error = nil;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
		/*
		 Replace this implementation with code to handle the error appropriately.
		 
		 abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
		 
		 Typical reasons for an error here include:
		 * The persistent store is not accessible
		 * The schema for the persistent store is incompatible with current managed object model
		 Check the error message to determine what the actual problem was.
		 */
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		abort();
    }    
	[storeUrl release];
    return persistentStoreCoordinator;
}


#pragma mark -
#pragma mark Application's Documents directory

/**
 Returns the path to the application's Documents directory.
 */
- (NSString *)applicationDocumentsDirectory {
	return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}


#pragma mark -
#pragma mark Memory management

- (void)dealloc {
	
    [managedObjectContext release];
    [managedObjectModel release];
    [persistentStoreCoordinator release];
    
	[dataManager release];
	
	[tabBarController release];
	[navigationController release];
	[window release];
	[super dealloc];
}


@end

